#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys, datetime, json

import logging

from xpy3lib.utils import db_utils as util
from xpy3lib.XLogger import XLogger
from xpy3lib.utils.XUtils import XUtils

from sicut.config import app_config

from sicut.CutJob import CutJob


def run(profile='prod', run_immediately=True):
    status = 0
    try:
        info = XUtils.get_git_info()
    except Exception as e:
        info = {'message': 'no_git'}
    # NOTE set the log-level via profile in config.py
    level = logging.WARNING if profile == 'prod' else logging.NOTSET
    config = app_config[profile]
    XLogger.getInstance(p_level=level, p_name_key_word=config.APPLICATION_NAME).logger.warning(
        '\n%s' % json.dumps(info, sort_keys=True, indent=4))

    try:
        db_conn_mpp = util.getConnectionDb2(config.DB_HOST_MPP_DB2,
                                            config.DB_PORT_MPP_DB2,
                                            config.DB_DBNAME_MPP_DB2,
                                            config.DB_USER_MPP_DB2,
                                            config.DB_PASSWORD_MPP_DB2)
        XLogger.getInstance().logger.warning('connect db_conn_mpp success?????????????????')
    except Exception as e:
        db_conn_mpp = None
        XLogger.getInstance().logger.error(str(e))
        status = 1

    if run_immediately:
        run_job(p_config=config, p_db_conn_mpp=db_conn_mpp)
    try:
        # close
        util.closeConnection(db_conn_mpp)
    except Exception as e:
        XLogger.getInstance().logger.error(str(e))
        status = 1

    return 0


def run_job(p_config=None, p_db_conn_mpp=None):
    # data type是 0 D M。分别是 实时、每日、每月
    p_data_type = '0'
    p_unit = 'Q161'
    p_account = '1001'
    p_cost_center = 'MIDF'
    p_account_period_start = '20210225220000'
    p_account_period_end = '20210226220000'

    CutJob(p_config=p_config, p_db_conn_mpp=p_db_conn_mpp).execute()
